
import time, datetime
from pymongo import MongoClient
from bson import ObjectId
import pymysql
import traceback

dbs = {
    "mongo-local": {
        "host": "127.0.0.1",
        "port": 27017,
        "username": "brotherbaby",
        "password": "q1w2e3r4",
        "authSource": "mytest"
    },
    "tidb-ycs1y": {
        "host": "10.246.240.103",
        "port": 4000,
        "user": "ods_s1y_his_select",
        "password": "wxIoSJOkghDtRUGb",
        "db": "ods_s1y_his"
    }
}

mongodb_ins = MongoClient(**dbs["mongo-local"]).mytest
tidb_conn = pymysql.connect(**dbs["tidb-ycs1y"])
tidb_ins = tidb_conn.cursor()

def compare(my_pat_info, his_pat_info_list, card_id):
    anomalous_item = {
        "card_id": str(card_id),
        "xhhk_name": my_pat_info.get("name", ""),
        "xhhk_id_number": my_pat_info.get("id_number", ""),
        "xhhk_gender": my_pat_info.get("gender", ""),
        "xhhk_telephone": my_pat_info.get("telephone", ""),
        "xhhk_address": my_pat_info.get("address", ""),

        "his_name": "",
        "his_id_number": "",
        "his_gender": "",
        "his_telephone": "",
        "his_address": "",

        "his_nonexists": 0,
        "name_mismatch": 0,
        "id_number_mismatch": 0,
        "gender_mismatch": 0,
        "telephone_mismatch": 0,
        "address_mismatch": 0
    }
    if not his_pat_info_list:
        anomalous_item["his_nonexists"] = 1
        return anomalous_item, True

    his_pat_info = his_pat_info_list[0]
    his_pat_info_new = {
        "name": str(his_pat_info[1] or ""),
        "id_number": str(his_pat_info[2] or ""),
        "gender": str(his_pat_info[3] or ""),
        "telephone": str(his_pat_info[4] or ""),
        "address": str(his_pat_info[5] or ""),
    }
    anomalous_item["his_name"] = his_pat_info_new.get("name", "")
    anomalous_item["his_id_number"] = his_pat_info_new.get("id_number", "")
    anomalous_item["his_gender"] = his_pat_info_new.get("gender", "")
    anomalous_item["his_telephone"] = his_pat_info_new.get("telephone", "")
    anomalous_item["his_address"] = his_pat_info_new.get("address", "")

    is_mismatch = False
    my_fields = ["name", "id_number", "gender", "telephone", "address"]
    for f in my_fields:
        his_f_v = his_pat_info_new.get(f)
        if f == "gender":
            if my_pat_info.get(f) not in [1, 2, "1", "2"]:
                if my_pat_info.get(f) == "男":
                    his_f_v = "1"
                elif my_pat_info.get(f) == "女":
                    his_f_v = "2"
        elif f == "id_number":
            if str(my_pat_info.get(f, "")).upper() != str(his_f_v).upper():
                anomalous_item["id_number_mismatch"] = 1
                if not is_mismatch:
                    is_mismatch = True
                    continue
        if str(my_pat_info.get(f, "")) != str(his_f_v):
            anomalous_item[f + "_mismatch"] = 1
            if not is_mismatch:
                is_mismatch = True
    return anomalous_item, is_mismatch

def do_biz():
    start_time = int(time.mktime((datetime.datetime.now() - datetime.timedelta(days=10)).timetuple())) * 1000
    end_time = int(time.time()) * 1000
    while True:
        with open('compare.log', 'a') as f:
            print(start_time)
            f.write("\nstarting...%d" % start_time)
            f.close()
        mcs = mongodb_ins.XHHK_MedicalCard.find({"app_id": ObjectId("5b77eb906615b700151dc07d"),
                                                 "obsoleted": False,
                                                 "created_at": {"$gte": start_time, "$lt": end_time}})
        start_time -= 10 * 24 * 60 * 60 * 1000
        end_time -= 10 * 24 * 60 * 60 * 1000
        if not mcs:
            break

        # compare....
        for mc in mcs:
            try:
                if not (mc.get("patient_id") and mc.get("card_id")):
                    continue
                my_pat_info = mongodb_ins.XHHK_Patient.find_one({"_id": mc.get("patient_id")})
                if not my_pat_info:
                    continue
                tidb_ins.execute(
                    "select brid, brxm, sfzh, brxb, jtdh, hkdz from ms_brda where brid = '%s'" % mc.get("card_id"))
                his_pat_info = tidb_ins.fetchall()
                anomalous_item, is_mismatch = compare(my_pat_info, his_pat_info, mc.get("card_id"))
                if is_mismatch:
                    mongodb_ins.XHHK_ProblemPatInfo.insert_one(anomalous_item)
            except Exception:
                print(mc.get("_id"), traceback.format_exc())
                continue

def main():
    do_biz()

if __name__ == '__main__':
    main()
